//
//  AppDelegate.m
//  chanlin
//
//  Created by Ryan on 14-10-31.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "AppDelegate.h"

#import "CLNavigationController.h"
#import "CLDataModel.h"
#import "UMessage.h"
#import "CLGloble.h"
#import "UMSocial.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialQQHandler.h"
#import "ChangyanSDK.h"
#import "CLLoginInViewController.h"
#import "CLComentDataModel.h"
#import "CLGlobleDataModel.h"
#import "UMSocialWechatHandler.h"
#import "WXApi.h"
#import "SgrGCD.h"
#import "CLPushWindow.h"
#import "CLCoveryManager.h"
#import "ReadDocHistory.h"
#import "SDImageCache.h"
#import "CLLoginModel.h"
#import "CLURLCache.h"

#import "CLIntroduceViewController.h"
#import "CLNavigationController.h"

#import "CLCollectModel.h"
#import "MobClick.h"
#import "IFAudioPlayerManager.h"


#import "IlibJHStat.h"

@interface AppDelegate ()
@property (nonatomic, strong) CLIntroduceViewController *introduceVC;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [NSURLCache setSharedURLCache:[CLURLCache new]];
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    [CLGloble sharedInstance].globleWidth = screenRect.size.width; //屏幕宽度
    [CLGloble sharedInstance].globleHeight = screenRect.size.height;  //屏幕高度（无顶栏）
    CLMainViewController *main=[CLMainViewController new];
    CLNavigationController *navi=[[CLNavigationController alloc] initWithRootViewController:main];
    navi.mainController=main;
    UIWindow *mainwindow=[[UIWindow alloc] init];
    mainwindow.frame=[UIScreen mainScreen].bounds;
    self.window=mainwindow;
    self.window.rootViewController=navi;
    [self.window makeKeyAndVisible];
    [UMSocialData setAppKey:@"5497aabffd98c52f89000b18"];

 [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    [UMSocialQQHandler setQQWithAppId:@"1103945603" appKey:@"NBBJz9tTYgPFWq8n" url:@"http://www.chanlin.org"];
    
    
    [ChangyanSDK registerApp:@"cyruaVDf2"
                      appKey:@"9241687fc3d8cb4bcbc1ed758da47108"
                 redirectUrl:nil
        anonymousAccessToken:@"_1eNERSNS-mAYZprL3Lajn_mhGWkQXxHPqZaJ5TMpRw"];
    [ChangyanSDK setAllowSelfLogin:YES];
    [ChangyanSDK setLoginViewController:[CLLoginInViewController new]];
    [ChangyanSDK setAllowAnonymous:YES];
    [ChangyanSDK setAllowRate:NO];
    [ChangyanSDK setAllowUpload:NO];
  
    
    [UMessage startWithAppkey:@"5497aabffd98c52f89000b18" launchOptions:launchOptions];
    [WXApi registerApp:@"wx7cce0f5e75128474"];
    [UMSocialWechatHandler setWXAppId:@"wx7cce0f5e75128474"
                            appSecret:@"2dbd8cf301a02356115ea135a87c6b79"
                                  url:@"http://www.umeng.com/social"];
    [MobClick startWithAppkey:@"5497aabffd98c52f89000b18" reportPolicy:BATCH channelId:@"appstore"];
    
    if(![CLGlobleDataModel sharedInstance].isNotPush){
        [[CLGlobleDataModel sharedInstance] registPush];
    }
    
    [CLGloble sharedInstance].user=[CLUser deSave];
    
   // NSURLProtocol
    
   // NSURLCache
   
    [[SgrGCD sharedInstance] enqueueGloble:^{
        if(_isStrNotNull([CLGloble sharedInstance].user.token)){
            [ChangyanSDK loginSSO:[CLGloble sharedInstance].user.uid
                         userName:[CLGloble sharedInstance].user.nickName
                       profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr([CLGloble sharedInstance].user.groupId)]
                           imgUrl:[CLGloble sharedInstance].user.imgUrl
                    completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                        if(statusCode!=CYSuccess){
                            [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                  subMessage:@"建议注销重新登陆尝试"];
                        }
                    }];
        }
    }];
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (localNotif && [localNotif isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic=(NSDictionary *)localNotif;
        int type=[dic sgrGetIntForKey:@"type"];
        NSString *tid=[dic sgrGetStringForKey:@"id"];

    dispatch_after(0.2, dispatch_get_main_queue(), ^{
        [[CLGloble sharedInstance] doPush:type docId:tid];
    });
    }
    if(GlobleHeight>480)
    [self performSelector:@selector(showHelpView)];
    [[CLCoveryManager sharedInstance] showCovery];
    [[CLCoveryManager sharedInstance] updateCovery];
    
    [UMSocialQQHandler setSupportWebView:YES];
    
//    NSLog(@"%@",[UIFont systemFontOfSize:1].fontName);
//     NSLog(@"%@",[UIFont boldSystemFontOfSize:1].fontName);
    
   
   
    return YES;
}




- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if([[url absoluteString] hasPrefix:@"wx8b2030599240f886"]){
        [WXApi handleOpenURL:url delegate:[CLGlobleDataModel sharedInstance]];
    }else if([[url absoluteString] hasPrefix:@"orgchanlinnews://"] && [url absoluteString].length>18){
        NSArray *params=[[[url absoluteString] substringFromIndex:17] componentsSeparatedByString:@"&"];
        if(params.count>=3){
            NSString *first=[params sgrGetStringForIndex:0];
            if([first isEqualToString:@"goto"]){
                NSString *type=[params sgrGetStringForIndex:1];
                NSString *tid=[params sgrGetStringForIndex:2];
                dispatch_after(0.2, dispatch_get_main_queue(), ^{
                    [[CLGloble sharedInstance] doPush:[type intValue] docId:tid];
                });
                
            }
        }
    }else{
        return  [UMSocialSnsService handleOpenURL:url];
    }
    
    return NO;
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    //return  [UMSocialSnsService handleOpenURL:url];
    if([[url absoluteString] hasPrefix:@"wx8b2030599240f886"]){
        [WXApi handleOpenURL:url delegate:[CLGlobleDataModel sharedInstance]];
    }else if([[url absoluteString] hasPrefix:@"orgchanlinnews://"] && [url absoluteString].length>18){
        NSArray *params=[[[url absoluteString] substringFromIndex:17] componentsSeparatedByString:@"&"];
        if(params.count>=3){
            NSString *first=[params sgrGetStringForIndex:0];
            if([first isEqualToString:@"goto"]){
                NSString *type=[params sgrGetStringForIndex:1];
                NSString *tid=[params sgrGetStringForIndex:2];
                dispatch_after(0.2, dispatch_get_main_queue(), ^{
                    [[CLGloble sharedInstance] doPush:[type intValue] docId:tid];
                });
                
            }
        }
    }else{
        return  [UMSocialSnsService handleOpenURL:url];
    }
    
    return NO;
}

- (void) showHelpView {
    BOOL showComplete = [[CLGloble sharedInstance] isUserHelpShowComplete];
    if(showComplete)
    {
        return;
    }
    [CLGloble sharedInstance].helpShow = 1;

    CLIntroduceViewController *introduceVC=[CLIntroduceViewController new];
    self.introduceVC=introduceVC;
    // [[DispatchCenter rootController] addChildViewController:wcp];
    
    
    // 塞在主视图上方（正常状态下顶上还有个封面故事（即：新手引导位于第二层），绝逼不能放在主视图下面，否则就永无天日了）
    [self.window insertSubview:introduceVC.view aboveSubview:((CLNavigationController *)[self k_rootController]).mainController.view];
}

- (void)nilIntroduceVC{
    self.introduceVC=nil;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[ReadDocHistory shareInstance] save];
    [[IFAudioPlayerManager shareInstance] checkRegister];
    
    [[NSUserDefaults standardUserDefaults] setObject:[[CLGloble sharedInstance].supports allObjects] forKey:@"livesupport"];
    [NSUserDefaults standardUserDefaults];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[CLGlobleDataModel sharedInstance] updateMenu];
    [[CLLoginModel sharedInstance] reLogin];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    [[IFAudioPlayerManager shareInstance] remoteControlReceivedWithEvent:event];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[ReadDocHistory shareInstance] save];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    [[SDImageCache sharedImageCache] clearMemory];
}

// apns
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"token:%@",deviceToken);
    [UMessage registerDeviceToken:deviceToken];
   //418780246d627340134928731d3c34bf1674e18ec5df3ddd66520cf14c836987

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"wrong%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //[UMessage didReceiveRemoteNotification:userInfo];
    
    if ([UIApplication sharedApplication].applicationState ==UIApplicationStateActive)
    {
        NSString *str=[[userInfo sgrGetDictionaryForKey:@"aps"] sgrGetStringForKey:@"alert"];
        

        
        [[CLGloble sharedInstance] showAlertWithTitle:@"消息推送"
                                              message:str
                                                block:^(int buttonIndex) {
                                                    int type=[userInfo sgrGetIntForKey:@"type"];
                                                    NSString *tid=[userInfo sgrGetStringForKey:@"id"];
                                                    if(buttonIndex==1){
                                                        [[CLGloble sharedInstance] doPush:type docId:tid];
                                                    }
                                                }
                                    cancelButtonTitle:@"取消"
                                  confirmButtonTitles:@"确定"];
    }else
        if ([UIApplication sharedApplication].applicationState==UIApplicationStateBackground ||
            [UIApplication sharedApplication].applicationState==UIApplicationStateInactive) {
            int type=[userInfo sgrGetIntForKey:@"type"];
            NSString *tid=[userInfo sgrGetStringForKey:@"id"];
            [[CLGloble sharedInstance] doPush:type docId:tid];

        }
}

- (void)application:(UIApplication *)application
handleWatchKitExtensionRequest:(NSDictionary *)userInfo
              reply:(void (^)(NSDictionary *replyInfo))reply{
    
    UIBackgroundTaskIdentifier b=[application beginBackgroundTaskWithExpirationHandler:^{
        
    }];
    [[CLCollectModel sharedInstance] saveListDic:userInfo block:^(BOOL success) {
        
        if(reply){
            reply(@{@"status":@(success)});
        }
        [application endBackgroundTask:b];
    }];
    
    
}

@end
